package com.mnnu.service.impl;

import com.mnnu.mapper.DeptLogMapper;
import com.mnnu.mapper.DeptMapper;
import com.mnnu.mapper.EmpMapper;
import com.mnnu.pojo.Dept;
import com.mnnu.pojo.DeptLog;
import com.mnnu.service.DeptLogService;
import com.mnnu.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;


    @Override
    public List<Dept> list() {
        List<Dept> depts = deptMapper.list();
        return depts;
    }

    /**
     * 根据id删除部门，同时删除部门下的员工
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(Integer id) {
        try {
            // 删除目标部门
            deptMapper.deleteById(id);
            int i = 1 / 0;
            // 删除部门对应员工
            empMapper.deleteByDeptId(id);
        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行解散部门，此次解散部门id：" + id);
            deptLogService.insert(deptLog);
        }
    }

    /**
     * 添加部门
     * @param dept
     */
    @Override
    public void add(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        dept.setCreateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    /**
     * 根据id查询部门
     * @param id
     * @return
     */
    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    /**
     * 修改部门信息
     * @param dept
     */
    @Override
    public void modify(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.modify(dept);
    }
}
